<?php
class User
{
	private $_table_user 		= 'users';
	private $_table_user_fields = array('user_id', 'fullname', 'email', 'password', 'created', 'updated', 'ordering', 'active');
		
	static protected $_instance = null;
	
	/**
	 * Get object instance
	 */
	
	public static function getInstance()
	{
		if( null === self::$_instance ) {
			self::$_instance = new self();	
		}
		return self::$_instance;
	}
	
	/**
	 * Get user info 
	 * @param int $id
	 */
	
	public function getUser($id, $where = null)
	{
		$storage = My_Globals::getStorage();
		$select = $storage->select()
						->from($this->_table_user)
						->where('user_id = ?', $id);
		if($where != null) {
			$select->where($where);
		}
		return $storage->fetchRow($select);
	}
	
	/**
	 * Delete user
	 * @param int $id
	 */
	
	public function deleteUser($id)
	{
		$storage = My_Globals::getStorage();
		return $storage->delete($this->_table_user, $storage->quoteInto('user_id IN (?)', $id));
	}
	
	/**
	 * Save user
	 * @param array $data
	 */
	
	public function saveUser($data)
	{
		$storage = My_Globals::getStorage();
		$data = My_Globals::initData($this->_table_user_fields, $data);
		if(isset($data['password'])) {
			$data['password'] = md5($data['password']);
		}
		if(isset($data['user_id']) && $data['user_id'] > 0) {
			// Update
			$rs = $storage->update($this->_table_user, $data, 'user_id = '.$data['user_id']);
		} else {
			// Insert
			$rs = $storage->insert($this->_table_user, $data);
		}
		// Clean
		unset($data);
		// Return
		return $rs;
	}
	
	/**
	 * Get list users
	 * @param int $page
	 * @param int $limit
	 */
	
	public function getUserList($page = null, $limit = null, $where = null)
	{
		// Set page
		if($page == 0) $page = 1;
		$storage = My_Globals::getStorage();
		$select = $storage->select()
						->from($this->_table_user, '*');
						
		if($limit) {
			$select->limitPage($page, $limit);
		}
		if($where != null) {
			$select->where($where);
		}
		$select->order(array('ordering ASC', 'email ASC'));
		return $storage->fetchAll($select);
	}
	
	/**
	 * Check Email Exist
	 * @param string $email
	 */
	
	public function checkEmailExist($email)
	{
		$storage = My_Globals::getStorage();
		$select = $storage->select()
						->from($this->_table_user, 'COUNT(*) AS total')
						->where($storage->quoteInto('email = ?', $email));
		$row = $storage->fetchRow($select);
		if($row['total']) {
			return true;
		}
		return false;
	}
	
	/**
	 * Check user login
	 * @param string $email
	 * @param string $password | lenght 32 charactors
	 */
	public function checkLogin($email, $password)
	{
		$storage = My_Globals::getStorage();
		$select = $storage->select()
						->from($this->_table_user, '*')
						->where($storage->quoteInto('email = ?', $email))
						->where('password = ?', md5($password))
						->where('active = ?', 1);
		$row = $storage->fetchRow($select);
		if(isset($row['user_id']) && $row['user_id'] > 0) {
			return $row;
		} else {
			return false;
		}
	}
}